//app.js
const API  = require('utils/api.js');
const AJAX = require('utils/ajax.js');
// 引入腾讯地图
var QQMapWx = require('utils/qqmap-wx-jssdk.js')
var qqmapsdk;
App({
  onLaunch: function () {
    console.log('onLaunch......初始化腾讯地图控件')
    // 进行初始化腾讯地图
    // 实例化API核心类
    qqmapsdk = new QQMapWx({
      key: API.api.qqMapKey
    })
    this.globalData.qqmapsdk = qqmapsdk
    let that = this
    wx.clearStorage();
    // 展示本地存储能力
    var timestamp = Date.parse(new Date());
    timestamp = timestamp / 1000;
    // console.log("当前时间戳为单位是秒：" + timestamp);
    wx.setStorageSync('expiredTime', timestamp)
    // 登录
    wx.login({
      success: res => {
        console.log('这里获取到code值：' + res.code)
        if(res.code && res.code != '') {
          // 发送 res.code 到后台换取 openId, sessionKey, unionId
          that.userLoginCode(res.code).then(function(response) {
            if (that.callback) {
              console.log('app request....')
              that.callback();
            }
          })          
        }
      }
    })
  },
  // 对后端进行访问
  userLoginCode: function (code) {
    let that = this
    return new Promise((resolve,reject) => {
      let requestUrl = API.api.users + '?code=' + code;
      AJAX.getRequest(requestUrl,false).then(function(response) {
        if (response.code == 200) {
          // 存储openId信息、用户信息
          wx.setStorageSync('openId', response.data.openId)
          wx.setStorageSync('userId', response.data.id)
          wx.setStorageSync('token', response.data.token)
          wx.setStorageSync('sendMessage', response.data.sendMessage)
          that.globalData.token = response.data.token
        }
        resolve()
      })
    })
  },
  getSetting:function() {
    return new Promise((resolve, reject) => {
      wx.getSetting({
        success: res => {
          if (res.authSetting['scope.userInfo']) {
            // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
            wx.getUserInfo({
              success: res => {
                wx.setStorageSync('nickName', res.userInfo.nickName)
                wx.setStorageSync('avatarUrl', res.userInfo.avatarUrl)
                // 可以将 res 发送给后台解码出 unionId
                return resolve(res.userInfo)
              }
            })
          }else{
            return reject()
          }
        }
      })
    })
  },
  updateUserInfo:function(userId,userInfo) {
      // 如果用户没有授权信息，则不作任何操作，等到用户需要在提示
    console.log(`获取到的数据信息是：` + userId + JSON.stringify(userInfo))
    userInfo.nickName
    let requestData = {}
    requestData.nickName = userInfo.nickName
    requestData.avatarUrl = userInfo.avatarUrl;
    let requestUrl = API.api.users + '/' + Number(userId)
    AJAX.postRequest(requestUrl,requestData,false).then(function(response) {
      console.log('用户信息更新成功啦')
    })        
  },
  globalData: {
    token: '',
    userInfo: null,
    qqmapsdk: '',
  }
})